//
//  WYCPersonalCenterController.m
//  51信用卡
//
//  Created by 中企互联 on 2017/11/4.
//  Copyright © 2017年 中企互联. All rights reserved.
//

#import "WYCPersonalCenterController.h"
#import "WYCMePhotoModel.h"

@interface WYCPersonalCenterController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

/** 遮盖View*/
@property(nonatomic,strong)UIView * coverView;

/** 模型*/
@property(nonatomic,strong)WYCMePhotoModel * MePhotoModel;
/** 显示View*/
@property(nonatomic,strong)UIView * showView;


/** 表视图*/
@property(nonatomic,strong)UITableView * tableView;


/** 头像*/
@property(nonatomic,strong)UIImageView * photoImage;


/**
 *头像
 */
@property (nonatomic,strong)UIImageView * saveimageView;


@end

@implementation WYCPersonalCenterController

- (void)viewDidLoad {
    [super viewDidLoad];
    //表视图创建
    [self setupTableView];
    
   //获取用户头像
    [self setupheadRequster];
}

- (void)setupheadRequster{
    
    NSString * str = [NSString stringWithFormat:@"%@token=%@",userPortraitDetail,[WYCAccountTool unarchivetoken]];
    [HttpTool POST:str params:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([[responseObject objectForKey:@"code"] intValue] == 0) {
            NSDictionary * dict = responseObject[@"result"];
            self.MePhotoModel = [WYCMePhotoModel mj_objectWithKeyValues:dict];
            if (self.MePhotoModel.imgUrl.length == 0){
                self.photoImage.image = [UIImage imageNamed:@"96"];
                
            }else{
                [self.photoImage sd_setImageWithURL:[NSURL URLWithString:self.MePhotoModel.imgUrl]];
            }
        }else{
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
            
        }
        [self setupNav];
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}
#pragma make --------->>表视图创建
- (void)setupTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, WYCcellHeight * 4) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
}
#pragma make --------->>setupNav
- (void)setupNav{
    
    self.view.backgroundColor = WYCGlobalBg;
    self.navigationItem.title = @"个人信息";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [self.navigationController.navigationBar setBarTintColor:wycMain];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTitle:@"保存" target:self action:@selector(PreservationClick)];
}

#pragma make -------->>数据代理  数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 3;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 320 * px;
    }else{
        return WYCcellHeight;
    }
    
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    tableView.tableFooterView = [[UIView alloc] init];
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"123"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"123"];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CGFloat cellXY = 40 * px;
    
    CGFloat celltitle = 80 * px;
    
    if (indexPath.row == 0) {
        UIView * cellView = [[UIView alloc] init];
        cellView.frame = CGRectMake(0, 0, ScreenWidth, WYCcellHeight);
        [cell addSubview:cellView];
        
        
        UILabel * photoLabel = [[UILabel alloc] init];
        photoLabel.frame = CGRectMake(cellXY, cellXY, 150 * px, 240 * px);
        photoLabel.text = @"头像";
        photoLabel.font = [UIFont systemFontOfSize:MiddleFont];
        [cellView addSubview:photoLabel];
        
        
        UIImageView * photoImageView = [[UIImageView alloc] init];
        photoImageView.frame = CGRectMake(ScreenWidth-90, cellXY, 70, 70);
        photoImageView.backgroundColor = [UIColor whiteColor];
        WYCLog(@"%@",self.MePhotoModel.imgUrl);
        [photoImageView sd_setImageWithURL:[NSURL URLWithString:self.MePhotoModel.imgUrl]];
        photoImageView.layer.masksToBounds = YES;
        [photoImageView setUserInteractionEnabled:YES];
        [photoImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPictureClick)]];
        photoImageView.layer.cornerRadius = photoImageView.width / 2;
        [cellView addSubview:photoImageView];
        self.photoImage = photoImageView;
        
    }
    else if (indexPath.row == 1){
        UIView * cellView = [[UIView alloc] init];
        cellView.frame = CGRectMake(0, 0, ScreenWidth, WYCcellHeight);
        [cell addSubview:cellView];
        
        
        UILabel * nameLabel = [[UILabel alloc] init];
        nameLabel.frame = CGRectMake(cellXY, cellXY, 150 * px, celltitle);
        nameLabel.text = @"昵称";
        nameLabel.font = [UIFont systemFontOfSize:MiddleFont];
        [cellView addSubview:nameLabel];
        
        
        UILabel * name = [[UILabel alloc] init];
        name.frame = CGRectMake(ScreenWidth-90, cellXY, 70, celltitle);
        name.textAlignment = NSTextAlignmentRight;
        name.textColor = [UIColor blackColor];
        name.text = [WYCAccountTool unarchiveuserName];
        name.font = [UIFont systemFontOfSize:MiddleFont];
        [cellView addSubview:name];
        
    }else{
        UIView * cellView = [[UIView alloc] init];
        cellView.frame = CGRectMake(0, 0, ScreenWidth, WYCcellHeight);
        [cell addSubview:cellView];
        
        
        UILabel * nameLabel = [[UILabel alloc] init];
        nameLabel.frame = CGRectMake(cellXY, cellXY, 180 * px, celltitle);
        nameLabel.text = @"手机号";
        nameLabel.font = [UIFont systemFontOfSize:MiddleFont];
        [cellView addSubview:nameLabel];
        
        UILabel * name = [[UILabel alloc] init];
        name.frame = CGRectMake(ScreenWidth-140, cellXY, 120, celltitle);
        name.textAlignment = NSTextAlignmentRight;
        name.textColor = [UIColor blackColor];
        name.text = [WYCAccountTool unarchivemobile];
        name.font = [UIFont systemFontOfSize:MiddleFont];
        [cellView addSubview:name];
        
    }
    return cell;
}
#pragma make -------->>保存
- (void)PreservationClick{
    WYCLogFunc;
    [self request];
    
}

#pragma make --------->>修改头像
- (void)showPictureClick{
    WYCLogFunc;
    //创建UIImagePickerController对象，并设置代理和可编辑
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.editing = YES;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    
  
    //创建sheet提示框，提示选择相机还是相册
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"请选择打开方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    //相机选项
    UIAlertAction * camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (@available(iOS 11.0, *)) {
            [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentAutomatic];
        }
        //选择相机时，设置UIImagePickerController对象相关属性
        imagePicker.sourceType =  UIImagePickerControllerSourceTypeCamera;
        imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        //跳转到UIImagePickerController控制器弹出相机
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];
    
    //相册选项
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (@available(iOS 11.0, *)) {
            [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentAutomatic];
        }
        //选择相册时，设置UIImagePickerController对象相关属性
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //跳转到UIImagePickerController控制器弹出相册
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];
    
    //取消按钮
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
        if (@available(iOS 11.0, *)) {
            [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
        }
    }];
    
    //添加各个按钮事件
    [alert addAction:camera];
    [alert addAction:photo];
    [alert addAction:cancel];
    
    //弹出sheet提示框
    [self presentViewController:alert animated:YES completion:nil];
}
//选取图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    UIImage *image1=[info objectForKey:UIImagePickerControllerEditedImage];
    //    self.saveimageView.image = image1;
    self.photoImage.image = image1;
    
    //选取完图片之后关闭视图
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)request{
    [SVProgressHUD showWithStatus:@"加载中..."];

    NSData * data = UIImageJPEGRepresentation(self.photoImage.image, 1);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"token"] = [WYCAccountTool unarchivetoken];
    params[@"base64Img"] = encodedImageStr;
    [HttpTool POST:saveUserPortrait params:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([[responseObject objectForKey:@"code"] intValue] == 0) {
            
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
            
        }
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:Failed];
    }];
}
@end

